package mkis.service.root.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import mkis.service.root.common.PageInfo;
import mkis.service.root.common.SearchInfo;
import mkis.service.root.constants.Constants;
import mkis.service.root.data.model.Member;
import mkis.service.root.service.MemberService;
import mkis.service.root.utils.HttpUtils;
import mkis.service.root.utils.MkisUtils;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value="/org/org_edit.do")
public class OrgEditCTR {
	
	@Resource(name="memberService")
	private MemberService memberService;
	
	@RequestMapping(method=RequestMethod.GET)
	public ModelAndView load(HttpServletRequest request,HttpServletResponse response,String mb_id) throws Exception{
		ModelAndView mav=new ModelAndView("org/org_edit");
		Map<String,Object> queryParam=new HashMap<String, Object>();
		
		Member member=null;
		String mode=null;
		if(mb_id==null ||"".equals(mb_id)){
			member=new Member();
			mode="insert";
		}else{
			queryParam.put("mb_id",mb_id);
			member=memberService.getMember(queryParam);
			mode="update";
		}
		
		mav.addObject("mode", mode);
		mav.addObject("member", member);
		return mav;
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public ModelAndView submit(HttpServletRequest request,HttpServletResponse response,Member member, String mode) throws Exception{
		ModelAndView mav=new ModelAndView("org/org_edit_complete");
		
		
		
		if("insert".equals(mode)){
			memberService.insertMember(member);
		} else{
			memberService.updateMember(member);
			//HttpSession session =request.getSession();
			//session.setAttribute(Constants.SESSION_MEMBER, member);
			Member ss_mb = MkisUtils.getMember(request);
			
			String edit_id=member.getMb_id();
			String ss_id=ss_mb.getMb_id();
			
			HttpSession session =request.getSession();
			
			
			if(ss_id.equals(edit_id)) {
				//자기자신 정보 수정시 세션정보 갱신
				session.removeAttribute(Constants.SESSION_MEMBER);
				
				ss_mb.setMb_name(member.getMb_name());
				ss_mb.setMb_hp(member.getMb_hp());
				
				session.setAttribute(Constants.SESSION_MEMBER, ss_mb);
			}
			
		}
		
		
		mav.addObject("mode", mode);
		return mav;
	}
	
}
